<?php

namespace catchAdmin\drug\controller;

use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use app\common\model\DrugType as TypeModel;

class DrugType extends CatchController
{
    protected $type;

    public function __construct(TypeModel $type)
    {
        $this->type = $type;
    }

    /**
     * 列表
     * @time 2023年08月16日
     * @return \think\response\Json
     */
    public function index(): \think\response\Json
    {
        return CatchResponse::paginate($this->type->getList());
    }

    /**
     * 新增
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function save(CatchRequest $request): \think\response\Json
    {
        $req = $request->post();

        //是否存在数据
        $is_existence = $this->type->where('deleted_at', 0)->field('value')->order('value', 'desc')->find();

        //存在数据，在原code上+1
        if ($is_existence) {
            $req["value"] = $is_existence['value'] + 1;
        } else {
            $req["value"] = 1;
        }
        $req['deleted_at'] = 0;
        return CatchResponse::success($this->type->addData($req));
    }

    /**
     * 更新
     * @param string $id 主键
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function update(string $id, CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success($this->type->saveData($id, $request->post()));
    }

    /**
     * 删除
     * @param string $id
     * @return \think\response\Json
     */
    public function delete(string $id): \think\response\Json
    {
        return CatchResponse::success($this->type->destroy($id));
    }
}